package com.ruoyi.web.controller.app;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * B端(合作商/经销商) 登录认证
 *
 * @author your_name
 */
// ... 省略 import ...

@RestController
@RequestMapping("/b-api")
public class BapiLoginController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        // 步骤1: 调用登录服务进行认证，这步会成功
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());

        // 步骤2: 【核心修正】根据用户名重新从数据库查询用户信息和角色
        SysUser user = userService.selectUserByUserName(loginBody.getUsername());
        Set<String> roles = permissionService.getRolePermission(user);

        // 检查该用户是否拥有 'partner' 或 'distributor' 角色
        if (!roles.contains("partner") && !roles.contains("distributor"))
        {
            return AjaxResult.error("您没有权限登录此平台");
        }

        // 步骤3: 返回Token
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
}